/*
# Rouleur Log - A log for cyclists.
# Copyright (C) 2006  Edward Copony (ecopony@gmail.com)
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
package com.blazingredfireball.rouleurlog.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.blazingredfireball.rouleurlog.business.RouteDelegate;
	import com.blazingredfireball.rouleurlog.model.RouleurlogModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import com.blazingredfireball.rouleurlog.vo.RouteVO;
	import flash.events.SQLEvent;
	import flash.data.SQLResult;

	public class GetRoutesCommand extends BaseCommand implements ICommand, IResponder
	{
		private var model : RouleurlogModelLocator = RouleurlogModelLocator.getInstance();
		
		public function execute(event:CairngormEvent):void
		{
			var delegate : RouteDelegate = new RouteDelegate(this);    
			delegate.getRoutes();
		}
		
		public function result(data:Object):void
		{
			var sqlEvent:SQLEvent = data as SQLEvent;
		  var result:SQLResult = sqlEvent.target.getResult();
			
			if (result.data != null)
      {
        var routes:ArrayCollection = new ArrayCollection();
        var route:RouteVO = null;
            
        for (var i:int = 0; i < result.data.length; i++)
        {
          route = new RouteVO();
          route.id = result.data[i].id;
          route.name = result.data[i].name;
          route.description = result.data[i].description;
          route.created_on = new Date(result.data[i].created_on);
          route.updated_on = new Date(result.data[i].updated_on);
          routes.addItem(route);
        }
        model.routes = routes; 
      }
		}
		
		public function fault( info : Object ) : void
		{
			if (model.databaseInitialized) Alert.show("Routes could not be retrieved!");
		}
	}
}